<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>浅拷贝与深拷贝 | dmf的个人博客</title><meta name="author" content="dmf"><meta name="copyright" content="dmf"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="描述">
<meta property="og:type" content="article">
<meta property="og:title" content="浅拷贝与深拷贝">
<meta property="og:url" content="https://gitee.com/dmf-c/blog/2021/07/31/js_file/ShallowDeep/index.html">
<meta property="og:site_name" content="dmf的个人博客">
<meta property="og:description" content="描述">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img1.baidu.com/it/u=3691791879,443411760&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=889">
<meta property="article:published_time" content="2021-07-30T16:00:00.000Z">
<meta property="article:modified_time" content="2022-10-12T07:23:34.339Z">
<meta property="article:author" content="dmf">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img1.baidu.com/it/u=3691791879,443411760&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=889"><link rel="shortcut icon" href="/blog/img/favicon.png"><link rel="canonical" href="https://gitee.com/dmf-c/blog/2021/07/31/js_file/ShallowDeep/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/blog/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/blog/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '浅拷贝与深拷贝',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-10-12 15:23:34'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">27</div></a><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">0</div></a><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">6</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw iconfont icon-shouyex"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-zuixinwenzhang_huaban"></i><span> 找文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/blog/categories/"><i class="fa-fw iconfont icon-fenlei1"></i><span> 分类</span></a></li><li><a class="site-page child" href="/blog/tags/"><i class="fa-fw iconfont icon-biaoqian1"></i><span> 标签</span></a></li><li><a class="site-page child" href="/blog/archives/"><i class="fa-fw iconfont icon-shijianzhou"></i><span> 归档</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://img1.baidu.com/it/u=3691791879,443411760&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=500&amp;h=889')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/blog/">dmf的个人博客</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw iconfont icon-shouyex"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-zuixinwenzhang_huaban"></i><span> 找文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/blog/categories/"><i class="fa-fw iconfont icon-fenlei1"></i><span> 分类</span></a></li><li><a class="site-page child" href="/blog/tags/"><i class="fa-fw iconfont icon-biaoqian1"></i><span> 标签</span></a></li><li><a class="site-page child" href="/blog/archives/"><i class="fa-fw iconfont icon-shijianzhou"></i><span> 归档</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">浅拷贝与深拷贝</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="fa-fw post-meta-icon far fa-calendar-alt"></i><span class="post-meta-label">发表于</span><time datetime="2021-07-30T16:00:00.000Z" title="发表于 2021-07-31 00:00:00">2021-07-31</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/Javascript/">Javascript</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="浅拷贝与深拷贝"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="浅拷贝与深拷贝"><a href="#浅拷贝与深拷贝" class="headerlink" title="浅拷贝与深拷贝"></a>浅拷贝与深拷贝</h2><ul>
<li><p>浅拷贝是创建一个新对象，这个对象有着原始对象属性值的一份精确拷贝。如果属性是基本类型，拷贝的就是基本类型的值，如果属性是引用类型，拷贝的就是内存地址 ，所以<strong>如果其中一个对象改变了这个地址，就会影响到另一个对象。</strong></p>
</li>
<li><p>深拷贝是将一个对象从内存中完整的拷贝一份出来,从堆内存中开辟一个新的区域存放新对象,且<strong>修改新对象不会影响原对象。</strong></p>
<pre><code>  var a1 = &#123;b: &#123;c: &#123;&#125;&#125;;

  var a2 = shallowClone(a1); // 浅拷贝方法
  a2.b.c === a1.b.c // true 新旧对象还是共享同一块内存

  var a3 = deepClone(a3); // 深拷贝方法
  a3.b.c === a1.b.c // false 新对象跟原对象不共享内存
</code></pre>
</li>
</ul>
<p>浅拷贝只复制指向某个对象的指针，而不复制对象本身，<strong>新旧对象还是共享同一块内存。</strong>但深拷贝会另外创造一个一模一样的对象，<strong>新对象跟原对象不共享内存</strong>，修改新对象不会改到原对象。</p>
<h2 id="赋值和深-x2F-浅拷贝的区别"><a href="#赋值和深-x2F-浅拷贝的区别" class="headerlink" title="赋值和深&#x2F;浅拷贝的区别"></a>赋值和深&#x2F;浅拷贝的区别</h2><p>这三者的区别如下，不过比较的前提都是<strong>针对引用类型</strong>：</p>
<ul>
<li><p>当我们把一个对象赋值给一个新的变量时，<strong>赋的其实是该对象的在栈中的地址，而不是堆中的数据。</strong>也就是两个对象指向的是同一个存储空间，无论哪个对象发生改变，其实都是改变的存储空间的内容，因此，两个对象是联动的。</p>
</li>
<li><p>浅拷贝：重新在堆中创建内存，拷贝前后对象的基本数据类型互不影响，但拷贝前后对象的引用类型因共享同一块内存，会相互影响。</p>
</li>
<li><p>深拷贝：从堆内存中开辟一个新的区域存放新对象，对对象中的子对象进行递归拷贝,拷贝前后的两个对象互不影响。</p>
</li>
</ul>
<p>下面的例子，对比赋值与深&#x2F;浅拷贝得到的对象修改后对原始对象的影响：</p>
<pre><code>// 对象赋值
let obj1 = &#123;
    name : &#39;喜羊羊&#39;,
    arr : [1,[2,3],4],
&#125;;
let obj2 = obj1;
obj2.name = &quot;美羊羊&quot;;
obj2.arr[1] =[5,6,7] ;
console.log(&#39;obj1&#39;,obj1) // obj1 &#123; name: &#39;美羊羊&#39;, arr: [ 1, [ 5, 6, 7 ], 4 ] &#125;
console.log(&#39;obj2&#39;,obj2) // obj2 &#123; name: &#39;美羊羊&#39;, arr: [ 1, [ 5, 6, 7 ], 4 ] &#125;

// 浅拷贝
let obj1 = &#123;
    name : &#39;喜羊羊&#39;,
    arr : [1,[2,3],4],
&#125;;
let obj3=shallowClone(obj1)
obj3.name = &quot;美羊羊&quot;;
obj3.arr[1] = [5,6,7] ; // 新旧对象还是共享同一块内存
// 这是个浅拷贝的方法
function shallowClone(source) &#123;
    var target = &#123;&#125;;
    for(var i in source) &#123;
        if (source.hasOwnProperty(i)) &#123;
            target[i] = source[i];
        &#125;
    &#125;
    return target;
&#125;
console.log(&#39;obj1&#39;,obj1) // obj1 &#123; name: &#39;喜羊羊&#39;, arr: [ 1, [ 5, 6, 7 ], 4 ] &#125;
console.log(&#39;obj3&#39;,obj3) // obj3 &#123; name: &#39;美羊羊&#39;, arr: [ 1, [ 5, 6, 7 ], 4 ] &#125;

// 深拷贝
let obj1 = &#123;
    name : &#39;喜羊羊&#39;,
    arr : [1,[2,3],4],
&#125;;
let obj4=deepClone(obj1)
obj4.name = &quot;美羊羊&quot;;
obj4.arr[1] = [5,6,7] ; // 新对象跟原对象不共享内存
// 这是个深拷贝的方法
function deepClone(obj) &#123;
    if (obj === null) return obj;
    if (obj instanceof Date) return new Date(obj);
    if (obj instanceof RegExp) return new RegExp(obj);
    if (typeof obj !== &quot;object&quot;) return obj;
    let cloneObj = new obj.constructor();
    for (let key in obj) &#123;
    if (obj.hasOwnProperty(key)) &#123;
        // 实现一个递归拷贝
        cloneObj[key] = deepClone(obj[key]);
    &#125;
    &#125;
    return cloneObj;
&#125;
console.log(&#39;obj1&#39;,obj1) // obj1 &#123; name: &#39;喜羊羊&#39;, arr: [ 1, [ 2, 3 ], 4 ] &#125;
console.log(&#39;obj4&#39;,obj4) // obj4 &#123; name: &#39;美羊羊&#39;, arr: [ 1, [ 5, 6, 7 ], 4 ] &#125;
</code></pre>
<p><a target="_blank" rel="noopener" href="https://imgse.com/i/xUPqUI"><img src="https://s1.ax1x.com/2022/10/12/xUPqUI.png" alt="xUPqUI.png"></a></p>
<h2 id="浅拷贝的实现方式"><a href="#浅拷贝的实现方式" class="headerlink" title="浅拷贝的实现方式"></a>浅拷贝的实现方式</h2><h3 id="Object-assign"><a href="#Object-assign" class="headerlink" title="Object.assign()"></a>Object.assign()</h3><p>Object.assign() 方法可以把任意多个的源对象自身的可枚举属性拷贝给目标对象，然后返回目标对象。</p>
<pre><code>let obj1 = &#123; person: &#123;name: &quot;kobe&quot;, age: 41&#125;,sports:&#39;basketball&#39; &#125;;
let obj2 = Object.assign(&#123;&#125;, obj1);
obj2.person.name = &quot;wade&quot;;
obj2.sports = &#39;football&#39;
console.log(obj1); // &#123; person: &#123; name: &#39;wade&#39;, age: 41 &#125;, sports: &#39;basketball&#39; &#125;
</code></pre>
<h3 id="函数库-lodash-的-clone-方法"><a href="#函数库-lodash-的-clone-方法" class="headerlink" title="函数库 lodash 的_.clone 方法"></a>函数库 lodash 的_.clone 方法</h3><p>该函数库也有提供_.clone 用来做 Shallow Copy</p>
<pre><code>var _ = require(&#39;lodash&#39;);
var obj1 = &#123;
    a: 1,
    b: &#123; f: &#123; g: 1 &#125; &#125;,
    c: [1, 2, 3]
&#125;;
var obj2 = _.clone(obj1);
console.log(obj1.b.f === obj2.b.f);// true
</code></pre>
<h3 id="展开运算符…"><a href="#展开运算符…" class="headerlink" title="展开运算符…"></a>展开运算符…</h3><p>展开运算符是一个 es6 &#x2F; es2015 特性，它提供了一种非常方便的方式来执行浅拷贝，与 Object.assign ()的功能相同。</p>
<pre><code>let obj1 = &#123; name: &#39;Kobe&#39;, address:&#123;x:100,y:100&#125;&#125;
let obj2= &#123;... obj1&#125;
obj1.address.x = 200;
obj1.name = &#39;wade&#39;
console.log(&#39;obj2&#39;,obj2) // obj2 &#123; name: &#39;Kobe&#39;, address: &#123; x: 200, y: 100 &#125; &#125;
</code></pre>
<h3 id="Array-prototype-concat"><a href="#Array-prototype-concat" class="headerlink" title="Array.prototype.concat()"></a>Array.prototype.concat()</h3><pre><code>let arr = [1, 3, &#123;
    username: &#39;kobe&#39;
    &#125;];
let arr2 = arr.concat();
arr2[2].username = &#39;wade&#39;;
console.log(arr); //[ 1, 3, &#123; username: &#39;wade&#39; &#125; ]
</code></pre>
<h3 id="Array-prototype-slice"><a href="#Array-prototype-slice" class="headerlink" title="Array.prototype.slice()"></a>Array.prototype.slice()</h3><pre><code>let arr = [1, 3, &#123;
    username: &#39; kobe&#39;
    &#125;];
let arr3 = arr.slice();
arr3[2].username = &#39;wade&#39;
console.log(arr); // [ 1, 3, &#123; username: &#39;wade&#39; &#125; ]
</code></pre>
<h2 id="深拷贝的实现方式"><a href="#深拷贝的实现方式" class="headerlink" title="深拷贝的实现方式"></a>深拷贝的实现方式</h2><h3 id="JSON-parse-JSON-stringify"><a href="#JSON-parse-JSON-stringify" class="headerlink" title="JSON.parse(JSON.stringify())"></a>JSON.parse(JSON.stringify())</h3><pre><code>let arr = [1, 3, &#123;
    username: &#39; kobe&#39;
&#125;];
let arr4 = JSON.parse(JSON.stringify(arr));
arr4[2].username = &#39;duncan&#39;;
console.log(arr, arr4)
</code></pre>
<p>这也是利用 JSON.stringify 将对象转成 JSON 字符串，再用 JSON.parse 把字符串解析成对象，一去一来，新的对象产生了，而且对象会开辟新的栈，实现深拷贝。</p>
<p><strong>这种方法虽然可以实现数组或对象深拷贝,但不能处理函数和正则</strong>，因为这两者基于 JSON.stringify 和 JSON.parse 处理后，得到的正则就不再是正则（变为空对象），得到的函数就不再是函数（变为 null）了。</p>
<p>比如：</p>
<pre><code>let arr = [1, 3, &#123;
    username: &#39; kobe&#39;
&#125;,function()&#123;&#125;];
let arr4 = JSON.parse(JSON.stringify(arr));
arr4[2].username = &#39;duncan&#39;;
console.log(arr, arr4)
</code></pre>
<h3 id="函数库lodash的-cloneDeep方法"><a href="#函数库lodash的-cloneDeep方法" class="headerlink" title="函数库lodash的_.cloneDeep方法"></a>函数库lodash的_.cloneDeep方法</h3><p>该函数库也有提供_.cloneDeep用来做 Deep Copy</p>
<pre><code>var _ = require(&#39;lodash&#39;);
var obj1 = &#123;
    a: 1,
    b: &#123; f: &#123; g: 1 &#125; &#125;,
    c: [1, 2, 3]
&#125;;
var obj2 = _.cloneDeep(obj1);
console.log(obj1.b.f === obj2.b.f);// false
</code></pre>
<h3 id="jQuery-extend-方法"><a href="#jQuery-extend-方法" class="headerlink" title="jQuery.extend()方法"></a>jQuery.extend()方法</h3><p>jquery 有提供一個$.extend可以用来做 Deep Copy</p>
<pre><code>$.extend(deepCopy, target, object1, [objectN])//第一个参数为true,就是深拷贝

var $ = require(&#39;jquery&#39;);
var obj1 = &#123;
    a: 1,
    b: &#123; f: &#123; g: 1 &#125; &#125;,
    c: [1, 2, 3]
&#125;;
var obj2 = $.extend(true, &#123;&#125;, obj1);
console.log(obj1.b.f === obj2.b.f); // false
</code></pre>
<h3 id="手写递归方法"><a href="#手写递归方法" class="headerlink" title="手写递归方法"></a>手写递归方法</h3><p>递归方法实现深度克隆原理：<strong>遍历对象、数组直到里边都是基本数据类型，然后再去复制，就是深度拷贝。</strong></p>
<p>有种特殊情况需注意就是对象存在<strong>循环引用</strong>的情况，即对象的属性直接的引用了自身的情况，解决循环引用问题，我们可以额外开辟一个存储空间，来存储当前对象和拷贝对象的对应关系，当需要拷贝当前对象时，先去存储空间中找，有没有拷贝过这个对象，如果有的话直接返回，如果没有的话继续拷贝，这样就巧妙化解的循环引用的问题。<a target="_blank" rel="noopener" href="https://segmentfault.com/a/1190000020255831">如何写出一个惊艳面试官的深拷贝?</a></p>
<pre><code>function deepClone(obj, hash = new WeakMap()) &#123;
if (obj === null) return obj; // 如果是null或者undefined我就不进行拷贝操作
if (obj instanceof Date) return new Date(obj);
if (obj instanceof RegExp) return new RegExp(obj);
// 可能是对象或者普通的值  如果是函数的话是不需要深拷贝
if (typeof obj !== &quot;object&quot;) return obj;
// 是对象的话就要进行深拷贝
if (hash.get(obj)) return hash.get(obj);
let cloneObj = new obj.constructor();
// 找到的是所属类原型上的constructor,而原型上的 constructor指向的是当前类本身
hash.set(obj, cloneObj);
for (let key in obj) &#123;
    if (obj.hasOwnProperty(key)) &#123;
    // 实现一个递归拷贝
    cloneObj[key] = deepClone(obj[key], hash);
    &#125;
&#125;
return cloneObj;
&#125;
let obj = &#123; name: 1, address: &#123; x: 100 &#125; &#125;;
obj.o = obj; // 对象存在循环引用的情况
let d = deepClone(obj);
obj.address.x = 200;
console.log(d);
</code></pre>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://gitee.com/dmf-c/blog">dmf</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://gitee.com/dmf-c/blog/2021/07/31/js_file/ShallowDeep/">https://gitee.com/dmf-c/blog/2021/07/31/js_file/ShallowDeep/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://gitee.com/dmf-c/blog" target="_blank">dmf的个人博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"><div class="social-share" data-image="https://img1.baidu.com/it/u=3691791879,443411760&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=500&amp;h=889" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/blog/2021/08/14/js_file/Closure/"><img class="prev-cover" src="https://img1.baidu.com/it/u=3691791879,443411760&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=500&amp;h=889" onerror="onerror=null;src='/blog/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Javascript闭包</div></div></a></div><div class="next-post pull-right"><a href="/blog/2021/07/10/js_file/ScopeChain/"><img class="next-cover" src="https://img1.baidu.com/it/u=3691791879,443411760&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=500&amp;h=889" onerror="onerror=null;src='/blog/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">JavaScript作用域和作用域链</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="this.onerror=null;this.src='/blog/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">dmf</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">27</div></a><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">0</div></a><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">6</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xxxxxx"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">业精于勤，荒于嬉。</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B5%85%E6%8B%B7%E8%B4%9D%E4%B8%8E%E6%B7%B1%E6%8B%B7%E8%B4%9D"><span class="toc-number">1.</span> <span class="toc-text">浅拷贝与深拷贝</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%B5%8B%E5%80%BC%E5%92%8C%E6%B7%B1-x2F-%E6%B5%85%E6%8B%B7%E8%B4%9D%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="toc-number">2.</span> <span class="toc-text">赋值和深&#x2F;浅拷贝的区别</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B5%85%E6%8B%B7%E8%B4%9D%E7%9A%84%E5%AE%9E%E7%8E%B0%E6%96%B9%E5%BC%8F"><span class="toc-number">3.</span> <span class="toc-text">浅拷贝的实现方式</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Object-assign"><span class="toc-number">3.1.</span> <span class="toc-text">Object.assign()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%87%BD%E6%95%B0%E5%BA%93-lodash-%E7%9A%84-clone-%E6%96%B9%E6%B3%95"><span class="toc-number">3.2.</span> <span class="toc-text">函数库 lodash 的_.clone 方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B1%95%E5%BC%80%E8%BF%90%E7%AE%97%E7%AC%A6%E2%80%A6"><span class="toc-number">3.3.</span> <span class="toc-text">展开运算符…</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Array-prototype-concat"><span class="toc-number">3.4.</span> <span class="toc-text">Array.prototype.concat()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Array-prototype-slice"><span class="toc-number">3.5.</span> <span class="toc-text">Array.prototype.slice()</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B7%B1%E6%8B%B7%E8%B4%9D%E7%9A%84%E5%AE%9E%E7%8E%B0%E6%96%B9%E5%BC%8F"><span class="toc-number">4.</span> <span class="toc-text">深拷贝的实现方式</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#JSON-parse-JSON-stringify"><span class="toc-number">4.1.</span> <span class="toc-text">JSON.parse(JSON.stringify())</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%87%BD%E6%95%B0%E5%BA%93lodash%E7%9A%84-cloneDeep%E6%96%B9%E6%B3%95"><span class="toc-number">4.2.</span> <span class="toc-text">函数库lodash的_.cloneDeep方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#jQuery-extend-%E6%96%B9%E6%B3%95"><span class="toc-number">4.3.</span> <span class="toc-text">jQuery.extend()方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%89%8B%E5%86%99%E9%80%92%E5%BD%92%E6%96%B9%E6%B3%95"><span class="toc-number">4.4.</span> <span class="toc-text">手写递归方法</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/blog/2023/01/08/vue_file/vuenote/" title="vue3入门笔记"><img src="https://img1.baidu.com/it/u=1828439677,2166285235&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=400&amp;h=300" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="vue3入门笔记"/></a><div class="content"><a class="title" href="/blog/2023/01/08/vue_file/vuenote/" title="vue3入门笔记">vue3入门笔记</a><time datetime="2023-01-07T16:00:00.000Z" title="发表于 2023-01-08 00:00:00">2023-01-08</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/02/20/vue_file/comm/" title="vue组件间通信六种方式"><img src="https://img1.baidu.com/it/u=1828439677,2166285235&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=400&amp;h=300" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="vue组件间通信六种方式"/></a><div class="content"><a class="title" href="/blog/2022/02/20/vue_file/comm/" title="vue组件间通信六种方式">vue组件间通信六种方式</a><time datetime="2022-02-19T16:00:00.000Z" title="发表于 2022-02-20 00:00:00">2022-02-20</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/02/05/wxEcharts/" title="微信小程序使用 echarts"><img src="https://img1.baidu.com/it/u=1828439677,2166285235&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=400&amp;h=300" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="微信小程序使用 echarts"/></a><div class="content"><a class="title" href="/blog/2022/02/05/wxEcharts/" title="微信小程序使用 echarts">微信小程序使用 echarts</a><time datetime="2022-02-04T16:00:00.000Z" title="发表于 2022-02-05 00:00:00">2022-02-05</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/01/30/vue_file/vue_router/" title="vue-router学习"><img src="https://img1.baidu.com/it/u=1828439677,2166285235&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=400&amp;h=300" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="vue-router学习"/></a><div class="content"><a class="title" href="/blog/2022/01/30/vue_file/vue_router/" title="vue-router学习">vue-router学习</a><time datetime="2022-01-29T16:00:00.000Z" title="发表于 2022-01-30 00:00:00">2022-01-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/01/16/vue_file/vuex/" title="Vuex使用方法"><img src="https://img1.baidu.com/it/u=1828439677,2166285235&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=400&amp;h=300" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="Vuex使用方法"/></a><div class="content"><a class="title" href="/blog/2022/01/16/vue_file/vuex/" title="Vuex使用方法">Vuex使用方法</a><time datetime="2022-01-15T16:00:00.000Z" title="发表于 2022-01-16 00:00:00">2022-01-16</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By dmf</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/blog/js/utils.js"></script><script src="/blog/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>